#define _CRT_SECURE_NO_WARNINGS  1


class Solution
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        sort(nums.begin(), nums.end());

        vector<vector<int>> v;
        int key1 = 0;
        int key2 = 1;
        while (key1 < nums.size() - 1)
        {
            int key2 = key1 + 1;
            while (key2 < nums.size() - 1)
            {
                int left = key2 + 1;
                int right = nums.size() - 1;
                long long aim = (long long)target - nums[key1] - nums[key2];
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum > aim)
                        right--;
                    else if (sum < aim)
                        left++;
                    else
                    {
                        v.push_back({ nums[key1],nums[key2],nums[left++],nums[right--] });

                        while (left < right && nums[left] == nums[left - 1])
                        {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1])
                        {
                            right--;
                        }
                    }
                }
                key2++;
                while (key2 < nums.size() - 1 && nums[key2] == nums[key2 - 1])
                {
                    key2++;
                }
            }
            key1++;
            while (key1 < nums.size() - 1 && nums[key1] == nums[key1 - 1])
            {
                key1++;
            }
        }
        return v;
    }
};